import { Alert } from '../models/Prediction';
import { Storage } from '@kit.StorageKit';
import { vibrator } from '@kit.DeviceKit';
import { promptAction } from '@kit.ArkUI';

// 通知服务类
export class NotificationService {
  private static instance: NotificationService;
  private storageKeyPrefix = 'notification_';

  // 单例模式
  public static getInstance(): NotificationService {
    if (!NotificationService.instance) {
      NotificationService.instance = new NotificationService();
    }
    return NotificationService.instance;
  }

  // 创建通知
  async createAlert(alert: Omit<Alert, 'id' | 'timestamp' | 'isRead'>): Promise<Alert> {
    try {
      const newAlert: Alert = {
        ...alert,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        timestamp: new Date(),
        isRead: false
      };
      
      // 获取用户的所有通知
      const alerts = await this.getUserAlerts(alert.patientId);
      alerts.unshift(newAlert);
      
      // 保存通知
      await Storage.setOrCreate(this.storageKeyPrefix + alert.patientId, JSON.stringify(alerts));
      
      // 触发通知
      await this.triggerAlert(newAlert);
      
      return newAlert;
    } catch (error) {
      console.error('创建通知失败:', error);
      throw error;
    }
  }

  // 触发通知
  private async triggerAlert(alert: Alert): Promise<void> {
    try {
      // 根据通知方式触发不同的提醒
      if (alert.alertMethod.includes('popup')) {
        await this.showPopupAlert(alert);
      }
      
      if (alert.alertMethod.includes('sms')) {
        // 实际应用中需要调用短信发送API
        console.log('发送短信通知:', alert.title, alert.message);
      }
      
      if (alert.alertMethod.includes('voice')) {
        // 实际应用中需要调用语音播报API
        console.log('语音播报通知:', alert.title, alert.message);
      }
      
      // 震动提醒
      await this.vibrate();
    } catch (error) {
      console.error('触发通知失败:', error);
    }
  }

  // 显示弹窗提醒
  private async showPopupAlert(alert: Alert): Promise<void> {
    try {
      // 根据严重程度设置不同的样式和行为
      switch (alert.severity) {
        case 'danger':
          await promptAction.showDialog({
            title: '⚠️ 紧急提醒',
            message: `${alert.title}\n${alert.message}`,
            buttons: [
              {
                text: '联系医生',
                action: () => {
                  console.log('用户选择联系医生');
                  // 跳转到联系医生页面
                }
              },
              {
                text: '知道了',
                action: () => {
                  console.log('用户关闭紧急提醒');
                }
              }
            ],
            cancel: () => {
              console.log('用户取消紧急提醒');
            }
          });
          break;
        case 'warning':
          await promptAction.showDialog({
            title: '⚠️ 风险提醒',
            message: `${alert.title}\n${alert.message}`,
            buttons: [
              {
                text: '查看详情',
                action: () => {
                  console.log('用户查看风险详情');
                  // 跳转到风险详情页面
                }
              },
              {
                text: '稍后处理',
                action: () => {
                  console.log('用户稍后处理风险');
                }
              }
            ]
          });
          break;
        default:
          await promptAction.showToast({
            message: alert.message,
            duration: 3000
          });
          break;
      }
    } catch (error) {
      console.error('显示弹窗提醒失败:', error);
    }
  }

  // 震动提醒
  private async vibrate(): Promise<void> {
    try {
      await vibrator.vibrate(500); // 震动500毫秒
    } catch (error) {
      console.error('震动提醒失败:', error);
    }
  }

  // 获取用户通知
  async getUserAlerts(userId: string, isRead?: boolean): Promise<Alert[]> {
    try {
      const alertsData = await Storage.get(this.storageKeyPrefix + userId);
      let alerts: Alert[] = alertsData ? JSON.parse(alertsData) : [];
      
      // 如果指定了已读状态，进行过滤
      if (isRead !== undefined) {
        alerts = alerts.filter(alert => alert.isRead === isRead);
      }
      
      return alerts;
    } catch (error) {
      console.error('获取用户通知失败:', error);
      return [];
    }
  }

  // 标记通知为已读
  async markAlertAsRead(alertId: string, userId: string): Promise<boolean> {
    try {
      const alerts = await this.getUserAlerts(userId);
      const alertIndex = alerts.findIndex(alert => alert.id === alertId);
      
      if (alertIndex === -1) {
        return false;
      }
      
      alerts[alertIndex].isRead = true;
      await Storage.setOrCreate(this.storageKeyPrefix + userId, JSON.stringify(alerts));
      
      return true;
    } catch (error) {
      console.error('标记通知为已读失败:', error);
      return false;
    }
  }

  // 标记所有通知为已读
  async markAllAlertsAsRead(userId: string): Promise<boolean> {
    try {
      const alerts = await this.getUserAlerts(userId);
      alerts.forEach(alert => {
        alert.isRead = true;
      });
      
      await Storage.setOrCreate(this.storageKeyPrefix + userId, JSON.stringify(alerts));
      
      return true;
    } catch (error) {
      console.error('标记所有通知为已读失败:', error);
      return false;
    }
  }

  // 删除通知
  async deleteAlert(alertId: string, userId: string): Promise<boolean> {
    try {
      const alerts = await this.getUserAlerts(userId);
      const filteredAlerts = alerts.filter(alert => alert.id !== alertId);
      
      await Storage.setOrCreate(this.storageKeyPrefix + userId, JSON.stringify(filteredAlerts));
      
      return true;
    } catch (error) {
      console.error('删除通知失败:', error);
      return false;
    }
  }

  // 批量删除通知
  async deleteAlerts(alertIds: string[], userId: string): Promise<boolean> {
    try {
      const alerts = await this.getUserAlerts(userId);
      const filteredAlerts = alerts.filter(alert => !alertIds.includes(alert.id));
      
      await Storage.setOrCreate(this.storageKeyPrefix + userId, JSON.stringify(filteredAlerts));
      
      return true;
    } catch (error) {
      console.error('批量删除通知失败:', error);
      return false;
    }
  }

  // 获取未读通知数量
  async getUnreadAlertCount(userId: string): Promise<number> {
    try {
      const alerts = await this.getUserAlerts(userId, false);
      return alerts.length;
    } catch (error) {
      console.error('获取未读通知数量失败:', error);
      return 0;
    }
  }

  // 创建风险预警通知
  async createRiskAlert(patientId: string, title: string, message: string, recommendations?: string[]): Promise<Alert> {
    return this.createAlert({
      patientId,
      type: 'risk',
      title,
      message: `${message}\n\n建议: ${recommendations?.join('\n') || '请及时就医'}`,
      severity: 'danger',
      alertMethod: ['popup', 'sms', 'voice']
    });
  }

  // 创建任务提醒通知
  async createTaskAlert(patientId: string, title: string, message: string): Promise<Alert> {
    return this.createAlert({
      patientId,
      type: 'task',
      title,
      message,
      severity: 'warning',
      alertMethod: ['popup']
    });
  }

  // 创建医生消息通知
  async createDoctorAlert(patientId: string, doctorName: string, message: string): Promise<Alert> {
    return this.createAlert({
      patientId,
      type: 'doctor',
      title: `${doctorName}医生的消息`,
      message,
      severity: 'info',
      alertMethod: ['popup']
    });
  }

  // 创建系统通知
  async createSystemAlert(patientId: string, title: string, message: string): Promise<Alert> {
    return this.createAlert({
      patientId,
      type: 'system',
      title,
      message,
      severity: 'info',
      alertMethod: ['popup']
    });
  }

  // 设置通知偏好
  async setNotificationPreferences(userId: string, preferences: NotificationPreferences): Promise<boolean> {
    try {
      await Storage.setOrCreate(this.storageKeyPrefix + 'preferences_' + userId, JSON.stringify(preferences));
      return true;
    } catch (error) {
      console.error('设置通知偏好失败:', error);
      return false;
    }
  }

  // 获取通知偏好
  async getNotificationPreferences(userId: string): Promise<NotificationPreferences> {
    try {
      const preferencesData = await Storage.get(this.storageKeyPrefix + 'preferences_' + userId);
      return preferencesData ? JSON.parse(preferencesData) : this.getDefaultPreferences();
    } catch (error) {
      console.error('获取通知偏好失败:', error);
      return this.getDefaultPreferences();
    }
  }

  // 获取默认通知偏好
  private getDefaultPreferences(): NotificationPreferences {
    return {
      enablePopup: true,
      enableSMS: true,
      enableVoice: true,
      enableVibration: true,
      enableRiskAlerts: true,
      enableTaskReminders: true,
      enableDoctorMessages: true,
      enableSystemNotifications: true,
      quietHours: {
        enabled: false,
        startHour: 22,
        endHour: 7
      }
    };
  }
}

// 通知偏好模型
export interface NotificationPreferences {
  enablePopup: boolean;
  enableSMS: boolean;
  enableVoice: boolean;
  enableVibration: boolean;
  enableRiskAlerts: boolean;
  enableTaskReminders: boolean;
  enableDoctorMessages: boolean;
  enableSystemNotifications: boolean;
  quietHours: {
    enabled: boolean;
    startHour: number;
    endHour: number;
  };
}